<template>
	<view>
		<uni-file-picker 
			v-model="fileList"
			:disabled="disabled || !writable"
			:disablePreview="disablePreview"
			:delIcon="deletable"
			:autoUpload="true"
			:limit="limit"
			:fileMediatype="fileMediatype"
			@select="fileSelect"
			@success="fileSuccess"
			@fail="fileFail"
			@delete="fileDelete"
		/>
		<text v-if="required && validator" class="requiredMessage">{{ requiredMessage }}</text>
	</view>
</template>

<script>
import { getToken } from '../utils'
import uniFilePicker from '../uni-file-picker/uni-file-picker.vue'
export default {
	data() {
		return {
			validator: false,
			fileList: []
		};
	},
	components: { uniFilePicker },
	props: {
		value: {
			type: Array,
			default: () => []
		},
		required: {
			type: Boolean,
			default: false
		},
		requiredMessage: {
			type: String,
			default: '值不能为空'
		},
		disabled: {
			type: Boolean,
			default: false
		},
		writable: {
			type: Boolean,
			default: true
		},
		limit: {
			type: [Number, String],
			default: 3
		},
		action: {
			type: String,
			default: '/api/sys/file/webupload/upload?uploadPath=/formbuilder'
		},
		deletable: {
			type: Boolean,
			default: true
		},
		disablePreview: {
			type: Boolean,
			default: false
		},
		fileMediatype: {
			type: String,
			default: 'image'
		},
		serverUrl: {
			type: String,
			default: 'http://192.168.67.47:8080/xps-vue/app'
		},
		tokenKey: {
			type: String,
			default: 'token'
		}
	},
	watch: {
		value: {
			handler() {
				console.log(this.value, 'this.value-->>')
			},
			immediate: true,
			deep: true
		},
		fileList: {
			handler() {
				if(!this.fileList.length) {
					this.validator = true
				} else {
					this.validator = false
				}
			},
			immediate: true,
			deep: true
		}
	},
	methods: {
		// 选择文件后触发
		fileSelect({ tempFiles, tempFilePaths }) {
			console.log(tempFiles, 'tempFiles --- 选择文件后触发')
			console.log(tempFilePaths, 'tempFilePaths --- 选择文件后触发')
		},
		
		// 上传成功
		fileSuccess({ tempFiles, tempFilePaths }) {
			console.log(tempFiles, 'tempFiles --- 上传成功')
			console.log(tempFilePaths, 'tempFilePaths --- 上传成功')
		},
		
		// 上传失败
		fileFail({ tempFiles, tempFilePaths }) {
			console.log(tempFiles, 'tempFiles --- 上传失败')
			console.log(tempFilePaths, 'tempFilePaths --- 上传失败')
		},
		
		// 文件从列表移除
		fileDelete({ tempFile, tempFilePath }) {
			console.log(tempFile, 'tempFile --- 文件从列表移除')
			console.log(tempFilePath, 'tempFilePath --- 文件从列表移除')
		},
		
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: this.action.replace('/api', this.serverUrl),
					filePath: url,
					name: 'file',
					header: {
						[this.tokenKey]: getToken(this.tokenKey)
					},
					success: res => {
						resolve(res.data.data)
					}
				})
			})
		}
	}
}
</script>

<style scoped>
.requiredMessage {
	width: 100%;
	height: 50rpx;
	line-height: 50rpx;
	color: #f56c6c;
	font-size: 22rpx;
}
</style>
